import os
import platform

import flet as ft
import pyautogui
from flet_core import MainAxisAlignment, CrossAxisAlignment

from app_config import update_log, update_title
from get_user_post import download
from post_item_layout import PostItemLayout


def main(page: ft.Page):
    page.title = "短视频助手(v1.0.3)"
    screen_width, screen_height = pyautogui.size()
    page.window_center()
    page.window_resizable = False
    page.window_width = screen_width * 0.75
    page.window_height = screen_height * 0.75
    page.padding = 0
    page.is_download = False

    if platform.system() == "Darwin":
        download_path = os.path.join(os.environ.get("HOME"), "Downloads")
    elif platform.system() == "Windows":
        user_path = os.path.expanduser('~')
        download_path = os.path.join(user_path, "Downloads")
    download_dir = os.path.join(download_path, "抖音视频下载")

    def close_banner(e):
        page.banner.open = False
        page.update()

    page.banner = ft.Banner(
        bgcolor=ft.colors.AMBER_100,
        leading=ft.Icon(ft.icons.WARNING_AMBER_ROUNDED, color=ft.colors.AMBER, size=40),
        content=ft.Text(
            "请输入有效的抖音主页地址url或者搜索关键字"
        ),
        actions=[
            ft.TextButton("确定", on_click=close_banner)
        ],
    )

    def show_banner(content):
        page.banner.open = True
        page.banner.content = content
        page.update()

    page.snack_bar = ft.SnackBar(
        content=ft.Text("Hello, world!"),
        action="Alright!",
    )

    def add_clicked(e):
        if page.is_download:
            show_banner(ft.Text(
                "当前有任务正在下载中，请等待任务下载结束~"
            ))
        else:
            if new_task.value == "" or new_task.value is None:
                show_banner(ft.Text(
                    "请输入有效的抖音主页地址url或者搜索关键字"
                ))
            else:
                page.remove_at(0)
                if __name__ == '__main__':
                    page.add(ft.Container(
                        width=page.window_width,
                        height=page.window_height - page.appbar.toolbar_height,
                        content=ft.Column(
                            alignment=MainAxisAlignment.CENTER,
                            horizontal_alignment=CrossAxisAlignment.CENTER,
                            controls=[
                                ft.ProgressRing(width=40, height=40, color='#F14400', ),
                                ft.Text(height=4),
                                ft.Text("正在加载中...", size=14, )
                            ]
                        )
                    ))
                page.update()
                close_banner(None)

                def callback(post_info):
                    tasks_view.controls.append(
                        PostItemLayout(page, post_info, download_dir, True)
                    )
                    page.update()

                def finish():
                    page.is_download = False
                    page.update()

                def first_load():
                    page.remove_at(0)
                    page.add(tasks_view)
                    tasks_view.controls = []
                    page.update()

                def error():
                    page.is_download = False
                    new_task.value = ""
                    show_banner("下载出错了，请联系开发人员。")
                    page.update()

                page.is_download = True
                download(new_task.value, download_dir, first_load, callback, finish, error)

    def on_back(e):
        page.remove_at(0)
        page.add(empty_view)
        page.update()

    new_task = ft.TextField(
        expand=True,
        content_padding=12,
        value='https://www.douyin.com/user/MS4wLjABAAAAccLNBkDcpi-Q-cMiPRLDKZKtPDiERkyzFewt4_BkrIw?vid=7324256784212839714',
        hint_text="使用主页地址或者直接输入搜索关键字检索",
    )

    tasks_view = ft.GridView(expand=True, runs_count=6, child_aspect_ratio=0.78, spacing=0, padding=0, run_spacing=0)

    dlg_modal = ft.AlertDialog(
        modal=True,
        title=ft.Text("设置"),
        content=ft.Container(
            width=350,
            height=120,
            content=ft.Column(
                controls=[
                    ft.Checkbox(label="设置是否下载音频", value=True, ),
                    ft.Checkbox(label="设置是否下载封面图", value=True, ),
                    ft.Checkbox(label="设置是否将音频和封面图以文件夹分类", value=True, ),
                ]
            ),
        ),
        actions=[
            ft.TextButton("Yes", ),
            ft.TextButton("No", ),
        ],
        actions_alignment=ft.MainAxisAlignment.END,
        on_dismiss=lambda e: print("Modal dialog dismissed!"),
    )

    def open_dlg_modal(e):
        page.dialog = dlg_modal
        dlg_modal.open = True
        page.update()

    page.appbar = ft.AppBar(
        bgcolor=ft.colors.INDIGO_50,
        automatically_imply_leading=True,
        leading_width=page.window_width,
        elevation=2,
        toolbar_height=80,
        leading=ft.Row(
            expand=True,
            controls=[
                ft.Text(width=12, ),
                new_task,
                ft.FloatingActionButton(icon=ft.icons.SEARCH, on_click=add_clicked, tooltip="搜索"),
                ft.FloatingActionButton(icon=ft.icons.BACKSPACE, on_click=on_back, tooltip="返回上一级"),
                ft.FloatingActionButton(icon=ft.icons.SETTINGS, on_click=open_dlg_modal, tooltip="设置"),
                ft.Text(width=12, ),
            ],
        ),
    )

    empty_view = ft.Container(
        width=page.window_width,
        bgcolor=ft.colors.WHITE10,
        padding=12,
        height=page.window_height - page.appbar.toolbar_height,
        content=ft.Column(
            controls=[
                ft.Text(update_title, size=18, ),
                ft.Text(update_log, size=14, ),
            ]
        ),
    )

    page.add(empty_view)


ft.app(target=main)
